package com.liantuo.weixinproject.config.dao;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @author Sam Hong
 * @date 2018-11-02 09:58
 */
@Configuration
public class SessionFactoryConfiguration {
    //mybatis-config.xml 配置文件路径
    @Value("${mybatis_config_file}")
    private String mybatisConfigFilePath;
    //mybatis mapper 文件路径
    @Value("${mapper_path}")
    private String mapperPath;
    //实体类所在的路径
    @Value("${entity_package}")
    private String entityPackage;

    @Autowired
    @Qualifier("dataSource")
    private DataSource dataSource;

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactoryBean createSqlSeesionFactoryBean() throws IOException {
        SqlSessionFactoryBean sqlSeesionFactoryBean=new SqlSessionFactoryBean();
        sqlSeesionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath));
        PathMatchingResourcePatternResolver resolver=new PathMatchingResourcePatternResolver();
        String packageSearchPath=PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPath;
        sqlSeesionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));
        sqlSeesionFactoryBean.setDataSource(dataSource);
        sqlSeesionFactoryBean.setTypeAliasesPackage(entityPackage);
        return sqlSeesionFactoryBean;
    }
}
